// Package service
// Created by GoLand
// @User: lenora
// @Date: 2023/11/29
// @Time: 18:08

package service

import (
	"camp-homework/week02/internal/domain"
	"camp-homework/week02/internal/repository"
	"context"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type UserService struct {
	repo *repository.UserRepository
}

func NewUserService(repo *repository.UserRepository) *UserService {
	return &UserService{
		repo: repo,
	}
}

func (srv *UserService) Signup(ctx context.Context, u domain.UserBase) error {
	pwd, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(pwd)
	return srv.repo.Create(ctx, u)
}

func (srv *UserService) Login(ctx context.Context, userName, password string) (domain.UserBase, error) {
	u, err := srv.repo.FindByName(ctx, userName)
	if err == repository.ErrUserNotFound {
		return domain.UserBase{}, ErrInvalidUser
	}

	if err != nil {
		return domain.UserBase{}, err
	}
	//验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)); err != nil {
		return domain.UserBase{}, ErrInvalidUser
	}

	return u, nil
}

func (srv *UserService) Profile(ctx context.Context, uid uint64) (domain.User, error) {
	u, err := srv.repo.Profile(ctx, uid)
	if err == repository.ErrUserNotFound {
		return domain.User{}, ErrUserNotFound
	}

	if err != nil {
		return domain.User{}, err
	}
	return u, nil
}

func (srv *UserService) Edit(ctx *gin.Context, uid uint64, nickname, birth, desc string) error {
	_, err := srv.repo.Profile(ctx, uid)
	if err == repository.ErrUserNotFound {
		return ErrUserNotFound
	}

	if err != nil {
		return err
	}
	return srv.repo.Edit(ctx, uid, nickname, birth, desc)
}
